<%@page
	import="java.util.List,java.util.ArrayList,org.apache.commons.lang.StringUtils,
	java.util.Set,
	com.trw.trp.bean.*,
	com.trw.trp.util.*,
	com.trw.trp.bean.WorkflowBean,
	com.trw.trp.bean.OrderBean"%>
<%@ include file="header.jsp"%>

<%
UserBean currentUser = (UserBean)session.getAttribute("currentUser");
boolean isSuper = cUser.getRoleList().contains(RoleBean.SUPER_ADMIN_ROLE);
List<ModelDetail> modelDetailList = null;
List<ModelBean> modelList = null;
OrderBean order = (OrderBean) TRPUtil.getFromSession(TRPConstants.CURRENT_ORDER);
order.generateOrderStatusName();
List<Integer> statusList = new ArrayList<Integer>();
Set<Integer> statusSet = null;
if(order.getModelMap()!=null){
	statusSet = order.getModelMap().keySet();
}
if(statusSet!=null){	
	for(Integer status: statusSet){
		if(status <= order.getInputStatus()){
			statusList.add(status);
		}
	}
}
java.util.Collections.sort(statusList);

List<String> modelNames = new ArrayList<String>();
if(statusList.contains(1)){
	modelDetailList = order.getDetailMap().get(1);
	modelList = order.getModelMap().get(1);
	if(modelList!=null){
		for(ModelBean model:modelList){
			modelNames.add(model.getModelName());
		}
	}
}
%>

<style type="text/css">
.x-column-header-inner .x-column-header-text {
    white-space: normal;
}


.headerText {
	display: block;
	height: 150px;
	width: 150px;
	font-size: 13px;
	white-space: normal!important;
	vertical-align: bottom;
	-webkit-transform: rotate(-90deg);
	-moz-transform: rotate(-90deg);
	-o-transform: rotate(-90deg);
	filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

}

.headerText2 {
	display: block;
	height: 130px;
	width: 130px;
	font-size: 13px;
	white-space: normal;
	vertical-align: bottom;
	-webkit-transform: rotate(-90deg);
	-moz-transform: rotate(-90deg);
	-o-transform: rotate(-90deg);
	filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

.headerText3 {
	font-size: 13px;
	white-space: normal;
}

</style>

<table align="center" cellpadding="0" cellspacing="0" 
	width="99.9%" border="0">
	<tr><td align='center'>
		<div id="errorDiv"></div>
		<div id="successDiv"></div>
		</td>
	</tr>	
	<tr valign="top">
		<td id="modelDiv"></td>
	</tr>
</table>

<script type="text/javascript">
var transferWin,transferForm;
function doEdit(){
	document.location='editOrder.action?orderId='+<%=order.getOrderId() %>;
}

function doTransfer(){
	if(!transferWin){
		Ext.define('users', {
			extend: 'Ext.data.Model',
			fields: ['userId', 'name','tel','mobile','email']
		});
		var storeData = '[';
		<%for(String modelName:modelNames){%>
			storeData+='{"modelName":'+'"<%=modelName%>"'+'},';
		<%}%>
		if(storeData.length>1){
			storeData=storeData.substr(0,storeData.length-1);
		}
		storeData+=']';
		transferForm = Ext.create('Ext.form.Panel', {
			frame: true,
			forceFit:true,
			anchor:'100% 100%',
			items: [{
				fieldLabel: '<b>New Test Engineer *</b>',
				anchor:'100%',
				xtype:'combo',
				id:'testUserSelect',
				name:'testUserSelect',
				labelWidth:150,
				allowBlank:false,
				editable:false,
				queryMode: 'local',
				store: Ext.create('Ext.data.Store', {
					autoLoad:true,
					model: 'users',
					proxy : new Ext.data.HttpProxy( {
						type: 'ajax',
						url : 'getUsers.action',
						extraParams:{position:'Test Engineer',department:'OSS'},
						reader: {
							type: 'json',
							totalProperty : 'size',
							root : 'items',
							idProperty: 'userId'
						}
					}),
					listeners:{
						'load':function (store,records,successful,operation,eOpts){
							store.filterBy(function(record,recordId){
								return record.data.userId!=<%=cUser.getUserId()%>;
							});
						}
					}
				}),
				displayField: 'name',
				valueField: 'userId'
			},{
				xtype:'grid',
				id:'transferGrid',
				columns: [
					{ header: 'Model Name',  dataIndex: 'modelName', width: 150},
					{ header: 'Sample',  dataIndex: 'sample', width: 150,editor:{xtype:'textfield',allowBlank:false}},
					{ header: 'Fixture',  dataIndex: 'fixture', width: 150,editor:{xtype:'textfield',allowBlank:false}}
				],
				height: 100,
				loadMask: true,
				forceFit:true,
				autoScroll:true,
				store: Ext.create('Ext.data.Store', {
					fields: [{name:'modelName'},{name:'sample'},{name:'fixture'}],
					data: Ext.util.JSON.decode(storeData)
				}),
				plugins: [Ext.create('Ext.grid.plugin.RowEditing', {
					clicksToMoveEditor: 1
				})]
			},{
				anchor:'100%',
				xtype:'textarea',
				fieldLabel:'Comment',
				id:'transferComment',
				labelWidth:150,
				height:80
			}]
		});
		transferWin = Ext.create('Ext.Window', {
			title: 'Transfer Request',
			border:0,
			modal:true,
			buttonAlign : "center",
			layout:'anchor',
			width:480,
			height:280,
			items: [transferForm],
			closeAction: function(){
				transferWin.hide();
			},
			buttons: [{
				text: 'Transfer',
				handler: function() {
					var teUser = Ext.getCmp('testUserSelect').getValue();
					if(teUser==null||teUser==''){
						Ext.Msg.alert('Warning', 'Please select the new Test Engineer.');
						return;
					}
					var grid = Ext.getCmp('transferGrid');
					var fixtureStr='',sampleStr='';
					if(grid){
						var store = grid.getStore();
						if(store.getCount()>0){
							for(var i=0;i<store.getCount();i++){
								var record = store.getAt(i);
								if(record.data.sample==''|| record.data.fixture==''){
									Ext.Msg.alert('Warning','Please double click the grid and fill in sample&fixture for each model.');
									return;
								}
								fixtureStr+=record.data.fixture+',';
								sampleStr+=record.data.sample+',';
							}
						}
					}
					transferWin.hide();					
					Ext.getBody().mask('processing...');
					Ext.Ajax.request({
						url: 'transferOrder.action',
						params: {
							orderId:<%=order.getOrderId() %>,
							newTeUserId:teUser,
							sampleStr:sampleStr,
							fixtureStr:fixtureStr,
							comment:Ext.getCmp('transferComment').getValue(),
							to:Ext.getCmp('testUserSelect').displayTplData[0].email,
							cc:'<%=cUser.getEmail()%>',
							emailId:9
						},
						success: function(response){
							Ext.getBody().unmask();
							var result = Ext.util.JSON.decode(response.responseText);
							var btn;
							if(result.state==0){
								Ext.Msg.alert('Info', 'Transfered successfully! One email has been sent to the new Test Engineer.');
								btn = Ext.getCmp("btnApprove");
								if(btn){btn.hide();}
								btn = Ext.getCmp("btnReject");
								if(btn){btn.hide();}
								btn = Ext.getCmp("btnTransfer");
								if(btn){btn.hide();}
							}else{
								Ext.Msg.alert('Warning', 'Operation failed, please try again later!');
							}
						},
						failure: function(response){
							Ext.Msg.alert('Warning', response.responseText);
							Ext.getBody().unmask();
						}
					});	
				}
			},{
				text: 'Cancel',
				handler: function() {
					transferWin.hide();
				}
			}]	
		});
	}
	transferForm.getForm().reset();
	transferWin.show();
	
}

function doDel(){
	Ext.MessageBox.confirm('Confirm', 'Do you want to delete the request['+'<%=order.getOrderNumber()%>'+']?', function(btn){
		if(btn == 'yes'){
			Ext.getBody().mask('deleting...');
			Ext.Ajax.request({
				url: 'deleteOrder.action',
				params: {
					orderId:<%=order.getOrderId() %>
				},
				success: function(response){
					var result = Ext.util.JSON.decode(response.responseText);
					Ext.Msg.alert('Info', result.message);
					Ext.getBody().unmask();
					if(result.state==0){
						document.location='userProfile.action';
					}
				},
				failure: function(response){
					Ext.Msg.alert('Warning', response.responseText);
					Ext.getBody().unmask();
				}
			});	
		}
	});
}

function doNext(){
	Ext.MessageBox.confirm('Confirm', 'All the information in this page will be frozen after your confirmation! Still want to continue?', function(btn){
		if(btn == 'yes'){
			document.location='uploadTestPartsInfo.action';
		}
	});
}

function sendMail(url){
	Ext.fly('modelPanel').mask('sending email...');
	Ext.Ajax.request({
		url: 'sendEmail.action',
		params: {
			to: '<%=order.getGeneralInfo().getTestUser()==null?"":order.getGeneralInfo().getTestUser().getEmail()%>',
			cc: '<%=order.getGeneralInfo().getVvUser()==null?"":order.getGeneralInfo().getVvUser().getEmail()%>',
			emailId: <%out.print(order.getInputStatus()==3?8:1);%>
		},
		success: function(response){
			Ext.fly('modelPanel').unmask();
			var btn=document.getElementById("btnEdit");
			if(btn){
				btn.style.display="none";
			}
			btn=document.getElementById("btnNext");
			if(btn){
				btn.style.display="none";
			}
			btn=document.getElementById("btnDel");
			if(btn){
				btn.style.display="none";
			}
			var msg = Ext.util.JSON.decode(response.responseText);
			Ext.MessageBox.alert(msg.state==0?'Info':'Warning', msg.message);
		},
		failure: function(response){
			Ext.fly('modelPanel').unmask();
			var msg = Ext.util.JSON.decode(response.responseText);
			Ext.MessageBox.alert('Warning', msg.message);
		}
	});
}

function doReject(){
	Ext.MessageBox.show({
	   title: 'Reject Order',
	   msg: 'Comment:',
	   width:300,
	   buttons: Ext.MessageBox.OKCANCEL,
	   multiline: true,
	   fn: showResultText
   });
}

function showResultText(btn, text){
	if(btn == 'ok'){
		doApprove0(false,text);
	}
};

function doApprove(){
	Ext.MessageBox.confirm('Confirm', 'Do you want to approve the request?', function(btn){
		if(btn == 'yes'){
			doApprove0(true,'');
		}
	});	
}

function doApprove0(isApprove,comment){
	Ext.getBody().mask('processing...');
	Ext.Ajax.request({
	    url: 'approveOrder.action',
	    params: {
	    	isApprove: isApprove,
	    	orderId: '<%=order.getOrderId() %>',
			to: '<%=order.getUser().getEmail()%>',
			cc: '<%=order.getGeneralInfo().getVvUser()==null?"":order.getGeneralInfo().getVvUser().getEmail()%>',
			<%if(order.getInputStatus()==3){%>
			emailId: isApprove==true?6:7,
			<%}else{%>
			emailId: isApprove==true?2:3,
			<%}%>
			comment: comment
	    },
	    success: function(response){
	        var result = Ext.util.JSON.decode(response.responseText);
			Ext.MessageBox.alert('Info', result.message+'<br><br>Click <a href="viewPipeline.action">here</a> navigate to Pipeline screen.');
			var btn = Ext.getCmp("btnApprove");
			if(btn){btn.hide();}
			btn = Ext.getCmp("btnReject");
			if(btn){btn.hide();}
			btn = Ext.getCmp("btnTransfer");
			if(btn){btn.hide();}
			Ext.getBody().unmask();
	    },
		failure: function(){
			Ext.getBody().unmask();
		}
	});
}

Ext.onReady(function(){
var panel,templatePnl;
if(!panel){
	panel = Ext.createWidget('tabpanel', {
		id: 'modelPanel',
		renderTo: 'modelDiv',
		bodyStyle:'padding:0px ',
		defaultType: 'textfield',
		forceFit:true,
		layout: {
            type: 'table',
            columns: 1
        },
		items: [{
			xtype:'panel',
			title:'Genernal Information',
			frame:true,
			layout: {
					type: 'table',
					columns: 4,
					tableAttrs: {
						border:1,
						cellspacing:0,
						cellpadding:0,
						bordercolor:'white',
						style: {
							width: '100%'
						}
					}
				},
				defaultType: 'displayfield',
				defaults: {
					labelWidth:130
				},
				items:[{
					colspan:2,
					fieldLabel: 'TRP Number',
					value: '<%=(order.getOrderNumber()+"("+order.getStatusName()+")")%>'
				},{
					rowspan:4,
					text: 'Project Name',
					tdAttrs:{width:100},
					cls:'x-form-item',
					width:50,
					xtype: 'label'
				},{
					fieldLabel: 'Customer',
					value:'<%=order.getGeneralInfo().getCustomer()%>'
				},{
					colspan:2,
					fieldLabel: 'Created Date',
					value: '<%=TRPConstants.DATE_FORMAT.format(order.getCreatedDate())%>'
				},{
					fieldLabel: 'Project',
					value:'<%=order.getGeneralInfo().getProject()%>'
				},{
					colspan:2,
					fieldLabel: 'Phase',
					value:'<%=order.getGeneralInfo().getPhase()%>'
				},{
					fieldLabel: 'Product',
					value:'<%=order.getGeneralInfo().getProduct()%>'
				},{
					colspan:2,
					fieldLabel: 'Test Purpose',
					value:'<%=order.getGeneralInfo().getTestPurpose()==null?"":order.getGeneralInfo().getTestPurpose().replaceAll("'","&acute;").replaceAll("\n","<br>").replaceAll("\r","")%>'
				},{
					fieldLabel: 'Plant',
					value:'<%=order.getGeneralInfo().getPlant()%>'
				},{
					rowspan:2,
					text: 'Applicant',
					xtype:'label',
					cls:'x-form-item',
					width:100
				},{
					fieldLabel: 'Name',
					value: '<%=order.getUser().getName()%>'
				},{
					colspan:2,
					fieldLabel: 'Project Number',
					value:'<%=order.getGeneralInfo().getProjectNumber()%>'
				},{
					fieldLabel: 'Mobile/Tel',
					value: 'Tel:'+'<%=order.getUser().getTel()%>'+' Mobile:'+'<%=order.getUser().getMobile()%>'
				},{
					colspan:2,
					fieldLabel: 'Payer',
					value:'<%=order.getGeneralInfo().getPayer()%>'
				},{
					text: 'Test Engineer',
					rowspan:2,
					cls:'x-form-item',
					xtype:'label'
				},{
					fieldLabel: 'Name',
					value:'<%=order.getGeneralInfo().getTestUser()==null?"":order.getGeneralInfo().getTestUser().getName()%>'
				},{
					colspan:2,
					fieldLabel: 'Report mode',
					value:'<%=order.getGeneralInfo().getReportMode()%>'
				},{
					fieldLabel: 'Mobile/Tel'
					<%if(order.getGeneralInfo().getTestUser()!=null){%>
					,
					value: 'Tel:'+'<%=order.getGeneralInfo().getTestUser().getTel()%>'+' Mobile:'+'<%=order.getGeneralInfo().getTestUser().getMobile()%>'
					<%}%>
				},{
					colspan:2,
					fieldLabel: 'Report distribution',
					value:'<%=order.getGeneralInfo().getReportDistribution()%>'
				},{
					xtype: 'label',
					cls:'x-form-item',
					rowspan:2,
					text: 'V&V Engineer'
				},{
					fieldLabel: 'Name',
					value:'<%=order.getGeneralInfo().getVvUser()==null?"":order.getGeneralInfo().getVvUser().getName()%>'
				},{
					colspan:2,
					rowspan:4,
					fieldLabel:'Selected Models',
					value:'<%=modelNames%>'
				},{
					fieldLabel: 'Mobile/Tel'
					<%if(order.getGeneralInfo().getVvUser()!=null){%>
					,
					value: 'Tel:'+'<%=order.getGeneralInfo().getVvUser().getTel()%>'+' Mobile:'+'<%=order.getGeneralInfo().getVvUser().getMobile()%>'
					<%}%>
				}]
		},
			<% if(statusList.contains(1)){
				List<OrderBean.SampleInfo> sampleInfoList = order.getSampleInfoList();
				List<OrderBean.MatrixInfo> matrixInfoList = order.getMatrixInfoList();
				for(int k=0;k<modelList.size();k++){
					ModelBean model = modelList.get(k);
					ModelDetail detail = modelDetailList.get(k);
					if(model==null||detail==null){
						continue;
					}
					OrderBean.SampleInfo sampleInfo = null;
					if(sampleInfoList!=null){
						for(OrderBean.SampleInfo sampleInfo0:sampleInfoList){
							if(model.getClientUniqueId().equals(sampleInfo0.getClientUniqueId())){
								sampleInfo = sampleInfo0;break;
							}
						}
					}
					OrderBean.MatrixInfo matrixInfo = null;
					if(matrixInfoList!=null){
						for(OrderBean.MatrixInfo matrixInfo0:matrixInfoList){
							if(model.getClientUniqueId().equals(matrixInfo0.getClientUniqueId())){
								matrixInfo = matrixInfo0;break;
							}
						}
					}
			%>
		{
			xtype:'panel',
			title:'<%=model.getModelName()%>',
			listeners: {
				activate: function(tab){
					if(tab.items.length>0){
						return;
					}
					var uniqueId = '<%=model.getClientUniqueId()%>';
					var techInfoPnl = Ext.create('Ext.panel.Panel',{
						title:'<font size=3><b>Technical Information</b></font>',
						id:'techinfo_'+uniqueId,
						frame:true,
						collapsible:true,
						autoHeight:true
					});
					Ext.Ajax.request({
						url: 'getModelDetail.action',
						params: {
							rowNumber: <%=k%>,
							status:1
						},
						success: function(response){
							var detail = Ext.util.JSON.decode(response.responseText);
							for(var i=0;i<detail.sectionList.length;i++){
								var section = detail.sectionList[i];
								var sectionPanel = Ext.create('Ext.form.FieldSet', {
									title:'<font size=2><b>'+section.name+'</b></font>',
									autoHeight:true,
									forceFit:true,
									defaultType:'label',
									layout: {
										type: 'table',
										padding: 5,
										columns: section.cols,
										tableAttrs: {
											border:1,
											bordercolor:'white',
											width:'100%'
										}
									}
								});
								for(var j=0;j<section.fieldList.length;j++){
									var field = section.fieldList[j];
									if(field.fieldType==0||field.fieldType==11){
										sectionPanel.add({
											id:'p'+uniqueId+field.fieldId,
											width:field.width,
											cls:'x-form-item',
											colspan:field.cols,
											rowspan:field.rows,
											html:field.selectedValue==''?field.fieldName:field.selectedValue
										});	
									}else if(field.fieldType==3){
										var text = field.fieldName;
										if(field.selectedValue=='true'){
											text += ': Yes';
										}else{
											text += ': No';
										}
										sectionPanel.add({
											id:'p'+uniqueId+field.fieldId,
											width:field.width,
											cls:'x-form-item',
											colspan:field.cols,
											rowspan:field.rows,
											text:text
										});	
									}else if(field.fieldType==1||field.fieldType==2||field.fieldType==4||field.fieldType==5||field.fieldType==6||field.fieldType==7||field.fieldType==10){
										var text = '';
										if(field.fieldName!=''){
											text+=field.fieldName+": ";
										}
										if(field.selectedValue!=''){
											text+=field.selectedValue.replaceAll('&acute;','\'').replaceAll('\n','<br>');
										}
										if(field.fieldType==1){
											if(field.relatedValue!='null'&&field.relatedValue!=''){
												var cmp = Ext.getCmp('p'+uniqueId+field.relatedValue);
												if(cmp){
													cmp.setText(cmp.getText()+' '+text);
													continue;
												}	
											}
										}
										if(text.indexOf('<br>')>0){
											sectionPanel.add({
												id:'p'+uniqueId+field.fieldId,
												width:field.width,
												cls:'x-form-item',
												colspan:field.cols,
												rowspan:field.rows,
												html: text
											});
										}else{
											sectionPanel.add({
												id:'p'+uniqueId+field.fieldId,
												width:field.width,
												cls:'x-form-item',
												colspan:field.cols,
												rowspan:field.rows,
												text: text
											});
										}	
									}else if(field.fieldType==8){
										sectionPanel.add({
											xtype:'panel',
											id:'p'+uniqueId+field.fieldId,
											colspan:field.cols,
											rowspan:field.rows,
											border:0,
											width:field.width,
											height:field.height
										});
									}else if(field.fieldType==31){
										sectionPanel.add({
											xtype:'hidden',
											id:'p'+uniqueId+field.fieldId,
											colspan:field.cols,
											rowspan:field.rows,
											border:0
										});
									}else if(field.fieldType==32){
										sectionPanel.add({
											xtype:'grid',
											id:'p'+uniqueId+field.fieldId,
											colspan:field.cols,
											rowspan:field.rows,
											bodyStyle:{"background-color":"#DFE9F6"}, 
											store:{
												autoLoad:false,
												storeId:'store_'+uniqueId+field.fieldId,
												xtype:'store',
												fields:['fileName'],
												proxy : new Ext.data.HttpProxy( {
													type: 'ajax',
													url : 'getFiles.action',
													extraParams:{
														orderNumber:'<%=order.getOrderNumber()%>',
														type:'techinfo_'+field.fieldId+'_'+uniqueId
													},
													reader: {
														type: 'json',
														totalProperty : 'size',
														root : 'items'
													}
												})
											},
											columns: [{
												header: 'File Name',  
												dataIndex: 'fileName',
												flex:1,
												renderer:function(value,cellmeta,record,rowIndex,columnIdx,store){
													var fieldId=store.storeId.replaceAll('store_'+uniqueId,'');
													return '<a href="download.action?type=techinfo_'+fieldId+'_'+uniqueId+'&orderNumber='+'<%=order.getOrderNumber()%>'+'&fileName='+encodeURIComponent(value)+'">'+value+'</a>'
												}
											}],
											//height: field.height,
											width: field.width,
											autoScroll:true,
											hideHeaders:true,
											border:false
										});
									}else if(field.fieldType==33){
										var relObj = Ext.util.JSON.decode(field.relatedValue);
										var columns=new Array(),fields=new Array(),clm,clmName,require=false;
										if(relObj.clms){
											for(var i=0,k=0;i<relObj.clms.length;i++){
												clm = relObj.clms[i];
												clmName = clm.n.replaceAll(' ','');
												if(clm.r){
													require=clm.r;
												}
												if(clm.items){
													columns[i]={header:clm.n};
													var tempClms=new Array(),tempClm;
													for(var j=0;j<clm.items.length;j++){
														tempClm=clm.items[j];
														clmName = tempClm.n.replaceAll(' ','');
														if(tempClm.r){
															require=tempClm.r;
														}
														tempClms[j]={header:tempClm.n,dataIndex:clmName};
														fields[k++]={name:clmName};
													}
													columns[i].columns=tempClms;
												}else{
													columns[i]={header:clm.n,dataIndex:clmName};
													fields[k++]={name:clmName};
												}
											}
										}
										sectionPanel.add({
											xtype:'grid',
											id:'pgrid'+uniqueId+field.fieldId,
											autoHeight:true,
											bodyBorder:false,
											border:0,
											autoScroll:true,
											rowspan:field.rows,
											colspan:field.cols,
											forceFit:true,
											sortableColumns:false,
											enableColumnMove:false,
											enableColumnHide:false,
											store: Ext.create('Ext.data.Store', {
												fields: fields,
												data: Ext.util.JSON.decode('['+field.selectedValue+']')
											}),
											columns: columns
										});
									}else if(field.fieldType==100){
										sectionPanel.add({
											xtype:'box',
											border:0,
											height:20,
											bodyStyle:{"background-color":"#DFE9F6"}, 
											colspan:field.cols,
											rowspan:field.rows
										});
									}
								}	
								techInfoPnl.add(sectionPanel);
							}
							var tempComp,tempValue;
							if(detail.modelId==12){								
								if(techInfoPnl.query('#p'+uniqueId+'129')[0].getText()=='Default'){
									tempComp=techInfoPnl.query('#p'+uniqueId+'128')[0];
									tempValue=techInfoPnl.query('#p'+uniqueId+'133')[0].getText();
									if(tempValue=='same side view'){
										tempComp.update('<img height="'+tempComp.getHeight()+'" src="images/image2.GIF">');
									}else if(tempValue=='different side view'){
										tempComp.update('<img height="'+tempComp.getHeight()+'" src="images/image1.GIF">');
									}
								}else{
									var store = techInfoPnl.query('#p'+uniqueId+'165')[0].getStore();
									if(store.getCount()==0){
										store.load();
									}
								}
								techInfoPnl.query('#p'+uniqueId+'353')[0].getStore().load();
								techInfoPnl.query('#p'+uniqueId+'355')[0].getStore().load();
							}else if(detail.modelId==20){
								tempComp = techInfoPnl.query('#p'+uniqueId+'246')[0];
								if(tempComp.getText().indexOf('Coordinates')>-1){
									techInfoPnl.query('#p'+uniqueId+'274')[0].hide();
								}else{
									techInfoPnl.query('#p'+uniqueId+'247')[0].hide();
									techInfoPnl.query('#p'+uniqueId+'248')[0].hide();
									techInfoPnl.query('#p'+uniqueId+'273')[0].hide();
								}
								techInfoPnl.query('#p'+uniqueId+'277')[0].getStore().load();
								techInfoPnl.query('#p'+uniqueId+'339')[0].getStore().load();
							}else if(detail.modelId==21){
								tempComp = techInfoPnl.query('#p'+uniqueId+'288')[0];
								if(tempComp.getText().indexOf('Coordinates')>-1){
									techInfoPnl.query('#p'+uniqueId+'292')[0].hide();
								}else{
									techInfoPnl.query('#p'+uniqueId+'289')[0].hide();
									techInfoPnl.query('#p'+uniqueId+'290')[0].hide();
									techInfoPnl.query('#p'+uniqueId+'291')[0].hide();
								}
								techInfoPnl.query('#p'+uniqueId+'295')[0].getStore().load();
								techInfoPnl.query('#p'+uniqueId+'310')[0].getStore().load();
							}else if(detail.modelId==22){
								tempComp = techInfoPnl.query('#p'+uniqueId+'300')[0];
								if(tempComp.getText().indexOf('Coordinates')>-1){
									techInfoPnl.query('#p'+uniqueId+'304')[0].hide();
								}else{
									techInfoPnl.query('#p'+uniqueId+'301')[0].hide();
									techInfoPnl.query('#p'+uniqueId+'302')[0].hide();
									techInfoPnl.query('#p'+uniqueId+'303')[0].hide();
								}
								techInfoPnl.query('#p'+uniqueId+'307')[0].getStore().load();
								techInfoPnl.query('#p'+uniqueId+'194')[0].getStore().load();
							}else if(detail.modelId==23){
								tempComp = techInfoPnl.query('#p'+uniqueId+'324')[0];
								if(tempComp.getText().indexOf('Coordinates')>-1){
									techInfoPnl.query('#p'+uniqueId+'328')[0].hide();
								}else{
									techInfoPnl.query('#p'+uniqueId+'325')[0].hide();
									techInfoPnl.query('#p'+uniqueId+'326')[0].hide();
									techInfoPnl.query('#p'+uniqueId+'327')[0].hide();
								}
								techInfoPnl.query('#p'+uniqueId+'330')[0].getStore().load();
								techInfoPnl.query('#p'+uniqueId+'334')[0].getStore().load();
							}else if(detail.modelId==13){
								techInfoPnl.query('#p'+uniqueId+'362')[0].getStore().load();
								techInfoPnl.query('#p'+uniqueId+'364')[0].getStore().load();
							}else if(detail.modelId==14){
								//techInfoPnl.query('#p'+uniqueId+'373')[0].getStore().load();
								techInfoPnl.query('#p'+uniqueId+'375')[0].getStore().load();
							}
						},
						failure: function(response){
						}
					});
					tab.add(techInfoPnl);
					/*
					//display sampleinfo
					<%if(sampleInfo!=null){%>
					var sampleInfoPnl = Ext.create('Ext.panel.Panel',{
						title:'<font size=3><b>Sample Information</b></font>',
						frame:true,
						collapsible:true,
						autoHeight:true
					});
					<%
					if(model.getModelId()==12){%>
					var infoPnl = Ext.create('Ext.form.FieldSet',{
						title:'<font size=2><b>Internal Parts</b></font>',
						items:[{
							xtype:'grid',
							layout:'fit',
							forceFit:true,
							autoHeight:true,
							autoScroll:true,
							enableColumnHide:false,
							enableColumnResize:false,
							sortableColumns:false,
							enableColumnMove:false,
							columnLines:true,
							store: Ext.create('Ext.data.Store', {
								autoLoad:true,
								fields: [{name:'rowNumber'},{name:'partName'},{name:'side'},{name:'inflatorType'},{name:'testTemp'}],
								proxy: {
									type: 'ajax',
									url: 'getSampleInfo.action',
									extraParams: {
										idx: <%=k%>,
										sectionIdx:5
									},
									reader: {
										type: 'json',
										root: 'items',
										totalProperty: 'size'
									}
								}			
							}),
							columns: [
								{xtype: 'rownumberer',header:'No.',width: 40},
								{ header: 'Part Name',  dataIndex: 'partName', width: 200,align:"center"},
								{ header: 'Side',  dataIndex: 'side', width: 100,align:"center"},
								{ header: 'Test Temperature',  dataIndex: 'testTemp', width: 200,align:"center"},
								{ header: 'Inflator Type',  dataIndex: 'inflatorType', width: 100,align:"center"}
							]
						}]
					});
					sampleInfoPnl.add(infoPnl);
					tab.add(sampleInfoPnl);
					<%}}%>
					*/
					//display matrixInfo
					var matrixInfoPnl = Ext.create('Ext.panel.Panel',{
						title:'<font size=3><b>Matrix Information</b></font>',
						frame:true,
						collapsible:true,
						autoHeight:true
					});
					var mtxPnl;
					<%if(model.getModelId()==12&&matrixInfo!=null){%>
					mtxPnl = Ext.create('Ext.form.FieldSet',{
						layout: {
							type: 'table',
							columns: 1,
							tableAttrs: {
								border:0,
								width:'100%'
							}
						},
						items:[{
							xtype:'grid',
							layout:'fit',
							columnLines: true,
							forceFit: true,
							autoScroll:false,
							headerPosition:'top',
							enableColumnHide:false,
							enableColumnResize:false,
							sortableColumns:false,
							enableColumnMove:false,
							store: Ext.create('Ext.data.Store', {
								autoLoad:true,
								fields: [{name:'idx'},{name:'testNo'},{name:'testTemp'},{name:'side'},{name:'inflatorType'},
								 {name:'ignitionC'},{name:'ignitionCD'},{name:'ignitionR'},{name:'timeFRTI'},{name:'storageTemp'},
								 {name:'tolerance1'},{name:'min'},{name:'max'},{name:'restorageTime'},{name:'moduleMountingTime'},{name:'testTemperature'},
								 {name:'tolerance2'},{name:'comments'}],
								proxy: {
									type: 'ajax',
									url: 'getMatrix.action?idx=<%=k%>',
									reader: {
										type: 'json',
										root: 'items',
										totalProperty: 'size'
									}
								}
							}),
							columns: [{
								text: '<span class="headerText3">Test No</span>',
								width:30,
								height:150,
								dataIndex:'testNo',
								renderer: function(value,a,obj,idx){
									return idx+1;
								}	
							},{
								text: '<span class="headerText3">Test Temp</span>',
								width:35,
								dataIndex:'testTemp'
							},{
								text: '<span class="headerText3">Inflator Type</span>',
								width:60,
								flex:1,
								dataIndex:'inflatorType'
							},{
								text: '<span class="headerText3">Side</span>',
								width:50,
								flex:1,
								dataIndex:'side'
							},{
								header: '<span class="headerText3">Ignition Current:(A)</span>',
								width:70,
								dataIndex: 'ignitionC',
								renderer:columnWrap
							},{
								header: '<span class="headerText3">Ignition Current Duration: (ms)</span>',
								width:70,
								dataIndex: 'ignitionCD'
							},{
								header: '<span class="headerText3">Ignition Resistance: (&Omega;)</span>',
								width:70,
								dataIndex: 'ignitionR'
							},{
								header: '<span class="headerText3">Time from removal to ignition: (s)</span>',
								width:70,
								dataIndex: 'timeFRTI'
							},{
								header: '<span class="headerText3">Storage Temperature (&#8451;)</span>',
								width:70,
								dataIndex: 'storageTemp'
							},{
								header: '<span class="headerText3">Storage Time(h)</span>',
								columns:[{
									header: '<span class="headerText3">Min</span>',
									width:35,
									dataIndex: 'min'
								},{
									header: '<span class="headerText3">Max</span>',
									width:35,
									dataIndex: 'max'
								}]
							},{
								header: '<span class="headerText3">Restorage Time(min)</span>',
								width:70,
								dataIndex: 'restorageTime'
							},{
								header: '<span class="headerText3">Module mounting time(s)</span>',
								width:70,
								dataIndex: 'moduleMountingTime'
							},{
								header: '<span class="headerText3">Test Temperature (&#8451;)</span>',
								width:70,
								dataIndex: 'testTemperature'
							},{
								header: '<span class="headerText3">Comments</span>',
								flex:1,
								minWidth:65
							}]
						},{
							xtype:'label',
							cls:'x-form-item',
							html:'<br><br>Spare Parts:'
						},{
							xtype:'grid',
							columnLines: true,
							forceFit: true,
							autoScroll:false,
							headerPosition:'top',
							enableColumnHide:false,
							enableColumnResize:false,
							sortableColumns:false,
							enableColumnMove:false,
							columns: [{
								text: '<span class="headerText3">Test No</span>',
								width:50,
								height:150,
								flex:1,
								dataIndex:'testNo',
								renderer: function(value,a,obj,idx){
									return 'SP'+(idx+1);
								}	
							},{
								text: '<span class="headerText3">Test Temp</span>',
								width:50,
								flex:1,
								dataIndex:'testTemp'
							},{
								text: '<span class="headerText3">Inflator Type</span>',
								width:60,
								flex:1,
								dataIndex:'inflatorType'
							},{
								text: '<span class="headerText3">Side</span>',
								width:50,
								flex:1,
								dataIndex:'side'
							},{
								header: '<span class="headerText3">Ignition Current: (A)</span>',
								width:70,
								dataIndex: 'ignitionC'
							},{
								header: '<span class="headerText3">Ignition Current Duration: (ms)</span>',
								width:70,
								dataIndex: 'ignitionCD'
							},{
								header: '<span class="headerText3">Ignition Resistance: (&Omega;)</span>',
								width:70,
								dataIndex: 'ignitionR'
							},{
								header: '<span class="headerText3">Time from removal to ignition: (s)</span>',
								width:70,
								dataIndex: 'timeFRTI'
							},{
								header: '<span class="headerText3">Storage Temperature (&#8451;)</span>',
								width:70,
								dataIndex: 'storageTemp'
							},{
								header: '<span class="headerText3">Storage Time(h)</span>',
								columns:[{
									header: '<span class="headerText3">Min</span>',
									width:35,
									dataIndex: 'min'
								},{
									header: '<span class="headerText3">Max</span>',
									width:35,
									dataIndex: 'max'
								}]
							},{
								header: '<span class="headerText3">Restorage Time (min)</span>',
								width:70,
								dataIndex: 'restorageTime'
							},{
								header: '<span class="headerText3">Module mounting time (s)</span>',
								width:70,
								dataIndex: 'moduleMountingTime'
							},{
								header: '<span class="headerText3">Test Temperature (&#8451;)</span>',
								width:70,
								dataIndex: 'testTemperature'
							}],
							store: Ext.create('Ext.data.Store', {
								autoLoad:true,
								fields: [{name:'idx'},{name:'testNo'},{name:'testTemp'},{name:'side'},{name:'inflatorType'},
										 {name:'ignitionC'},{name:'ignitionCD'},{name:'ignitionR'},{name:'timeFRTI'},{name:'storageTemp'},
										 {name:'min'},{name:'max'},{name:'restorageTime'},{name:'moduleMountingTime'},{name:'testTemperature'}],
								proxy: {
									type: 'ajax',
									url: 'getSpareParts.action?idx=<%=k%>',
									reader: {
										type: 'json',
										root: 'items',
										totalProperty: 'size'
									}
								}
							})
						}]
					});
					<%}else if(model.getModelId()==20||model.getModelId()==21||model.getModelId()==22||model.getModelId()==23){%>
					mtxPnl = Ext.create('Ext.form.FieldSet',{
						items:[{
							xtype:'grid',
							title: 'Matrix Information',
							loadMask: true,
							forceFit:true,
							autoScroll:true,
							enableColumnHide:false,
							sortableColumns:false,
							columnLines:true,
							autoHeight:true,
							columns: [
								{xtype: 'rownumberer',header:'No.',width: 40},
								{header: '<span class="headerText3">Ignition Current (A)</span>',dataIndex: 'ignitionC',width:50},
								{header: '<span class="headerText3">Current Duration (ms)</span>',dataIndex: 'currentDur',width:50},
								{header: '<span class="headerText3">Frame Per Second</span>',dataIndex: 'framePerSec',width:50},
								{header: '<span class="headerText3">Video Record Time(ms)</span>',dataIndex: 'videoRecTime',width:50},
								{header: '<span class="headerText3">Temperature(&#8451;)</span>',dataIndex: 'temp',width:50},
								{header: '<span class="headerText3">Storage time(h)</span>',dataIndex: 'storageTime',width:50},
								{header: '<span class="headerText3">Dual Stage inflator</span>',dataIndex: 'dualStageInflator',width:50},
								{header: '<span class="headerText3">Stage Delay(ms)</span>',dataIndex: 'stageD',width:50},
							<%if(model.getModelId()==20||model.getModelId()==23){%>
								{header: 'Impact Dimension',
									columns:[{
										header: '<span class="headerText3">Length (mm)</span>',
										width:50,
										dataIndex: 'length'
									},{
										header: '<span class="headerText3">Width (mm)</span>',
										width:50,
										dataIndex: 'width'
									}]
								},
							<%}%>
							<%if(model.getModelId()==21){%>
								{header: '<span class="headerText3">Impact Type</span>',dataIndex: 'impactType',width:50},
							<%}else{%>
								{header: '<span class="headerText3">Impact Mass(kg)</span>',dataIndex: 'impactMass',width:50},
							<%}%>
							<%if(model.getModelId()==22){%>
								{header: '<span class="headerText3">Column Angle(&deg;)</span>',dataIndex: 'columnAngle',width:50},
							<%}%>
							<%if(model.getModelId()==23){%>
								{header: '<span class="headerText3">Push Distance</span>',dataIndex: 'PushDistance',width:50},
							<%}else{%>
								{header: '<span class="headerText3">Velocity</span>',dataIndex: 'Velocity',width:50},
							<%}%>
								{header: '<span class="headerText3">TestQuantity</span>',dataIndex: 'TestQuantity',width:50},
								{header: '<span class="headerText3">Position</span>',dataIndex: 'Position',width:50},
								{header: '<span class="headerText3">Temperature</span>',dataIndex: 'Temperature',width:50},
								{header: '<span class="headerText3">Module Parameter</span>',dataIndex: 'ModuleParameter',width:50}
							],
							store: Ext.create('Ext.data.Store', {
								autoLoad:true,
								fields: [{name:'ignitionC'},{name:'currentDur'},{name:'framePerSec'},{name:'videoRecTime'},{name:'temp'},{name:'storageTime'},
										 {name:'dualStageInflator'},{name:'stageD'},{name:'impactType'},{name:'length'},{name:'width'},{name:'impactMass'},{name:'columnAngle'},
										 {name:'Velocity'},{name:'PushDistance'},{name:'TestQuantity'},{name:'Position'},{name:'Temperature'},{name:'ModuleParameter'}],
								proxy: {
									type: 'ajax',
									url: 'getMatrix.action?idx=<%=k%>',
									reader: {
										type: 'json',
										root: 'items',
										totalProperty: 'size'
									}
								}
							})
						}]
					});
					<%}%>
					if(mtxPnl){
						matrixInfoPnl.add(mtxPnl);
					}
					tab.add(matrixInfoPnl);	
					var testPartInfoPnl = Ext.create('Ext.panel.Panel',{
						title:'<font size=3><b>Test Parts Information</b></font>',
						frame:true,
						collapsible:true,
						autoHeight:true,
						items:[{
							xtype:'displayfield',
							value:'Test Parts Information:'
						},{
							xtype:'grid',
							id:'fileGrid'+'<%=model.getClientUniqueId()%>',
							width:400,
							store:{
								autoLoad:true,
								xtype:'store',
								fields:['fileName'],
								proxy : new Ext.data.HttpProxy( {
									type: 'ajax',
									url : 'getFiles.action',
									extraParams:{
										orderNumber:'<%=order.getOrderNumber()%>',
										type:'matrixInfo'+'<%=model.getClientUniqueId()%>'
									},
									reader: {
										type: 'json',
										totalProperty : 'size',
										root : 'items'
									}
								})
							},
							columns: [{
								dataIndex: 'fileName',
								width:330,
								renderer:function(value){
									return '<a href="download.action?type=matrixInfo'+'<%=model.getClientUniqueId()%>'+'&orderNumber='+'<%=order.getOrderNumber()%>'+'&fileName='+encodeURIComponent(value)+'">'+value+'</a>'
								}
							}],
							autoScroll:true,
							hideHeaders:true,
							border:false
						},{
							xtype:'displayfield',
							value:'BOM Information:'
						},{
							xtype:'grid',
							id:'fileGrid2'+'<%=model.getClientUniqueId()%>',
							width:400,
							store:{
								autoLoad:true,
								xtype:'store',
								fields:['fileName'],
								proxy : new Ext.data.HttpProxy( {
									type: 'ajax',
									url : 'getFiles.action',
									extraParams:{
										orderNumber:'<%=order.getOrderNumber()%>',
										type:'matrixInfo2'+'<%=model.getClientUniqueId()%>'
									},
									reader: {
										type: 'json',
										totalProperty : 'size',
										root : 'items'
									}
								})
							},
							columns: [{
								dataIndex: 'fileName',
								width:330,
								renderer:function(value){
									return '<a href="download.action?type=matrixInfo2'+'<%=model.getClientUniqueId()%>'+'&orderNumber='+'<%=order.getOrderNumber()%>'+'&fileName='+encodeURIComponent(value)+'">'+value+'</a>'
								}
							}],
							autoScroll:true,
							hideHeaders:true,
							border:false
						}]
					});
					tab.add(testPartInfoPnl);	
				}
			}
		},		
			<%	}	
			}%>
		{
			xtype:'grid',
			title: 'Order History',
			forceFit: true,
			loadMask: true, 
			autoHeight:true,
			columns: [
				{ header: 'Action',  dataIndex: 'action'},
				{ header: 'Comment',  dataIndex: 'comment'},
				{ header: 'Action User',  dataIndex: 'changeUser'},
				{ header: 'Change Date',  dataIndex: 'changeDate'}
			],
			store: {
				autoLoad: false,
				fields:['action', 'comment', 'changeUser','changeDate'],
				proxy: {
					type: 'ajax',
					url: 'viewOrderHistory.action',  // url that will load data with respect to start and limit params
					reader: {
						type: 'json',
						root: 'items',
						totalProperty: 'size'
					}
				}
			},
			listeners: {
				activate: function(tab){
					var store = tab.getStore();
					if(store.getCount()==0){
						store.load({params:{orderId:'<%=order.getOrderId()%>'}});
					}
				}
			}
		}],
		buttonAlign:'center',
		buttons:[
		<%if(isSuper||(order.getUser().equals(cUser)&&(order.getStatus()<=0))){%>
		{
			text:'Delete',
			cls:'big-button',
			id:'btnDel',
			handler:doDel
		},
		<%}%>
		<%if(order.getUser().equals(cUser)){%>
		{
			text:'Send Mail',
			cls:'big-button',
			id:'btnSend',
			handler:sendMail
		},		
		<%	if(order.getStatus()==0||order.getStatus()==-2||order.getStatus()==2){%>	
		{
			text:'Edit',
			cls:'big-button',
			id:'btnEdit',
			handler:doEdit
		},		
			<%}%>	
		
		<%	if(order.getStatus()<3) {%>	
		{
			text:'Next',
			cls:'big-button',
			id:'btnNext',
			handler:doNext
		},
		<%	}
		}else if(currentUser.equals(order.getGeneralInfo().getTestUser())){
			if(order.getStatus()>=100){%>
		{
			text:'Approve',
			cls:'big-button',
			id:'btnApprove',
			handler:doApprove
		},
		<%	}
			if(order.getStatus()>=100||order.getStatus()>0&&order.getStatus()<10){%>
		{
			text:'Reject',
			cls:'big-button',
			id:'btnReject',
			handler:doReject
		},
		<%	}
			if(order.getStatus()>1){%>
		{
			text:'Transfer',
			cls:'big-button',
			id:'btnTransfer',
			handler:doTransfer
		},
		<%	}%>
		/*{
			text:'Next',
			cls:'big-button',
			id:'btnNext2',
			hidden:<%=order.getStatus()!=2%>,
			handler:doNext2
		},*/
		<%}%>	
		<%if(modelList!=null&&!modelList.isEmpty()){%>
		{
			cls:'big-button',
			text:'Download Matrix',
			width: 130,
			handler:function(){
				Ext.getBody().mask('downloading...');
				Ext.Ajax.request({
					url: 'generateMatrix.action',
					params: {
						orderNumber: '<%=order.getOrderNumber()%>'
					},
					success: function(response){
						document.location='download.action?type=matrix'+'&orderNumber='+'<%=order.getOrderNumber()%>'+'&fileName=matrix.pdf';
						Ext.getBody().unmask();
					},
					failure: function(response){
						Ext.getBody().unmask();
						Ext.MessageBox.alert('Warning', 'Download matrix failed, please try again.');
					}
				});
			}
		},
		<%}%>
		{
			cls:'big-button',
			text:'Save as Template',
			width: 130,
			handler:function(){
				if(!templatePnl){
					var templateForm = Ext.create('Ext.form.Panel', {
						frame: true,
						bodyStyle:'padding:5px 5px 0',
						forceFit:true,
						border:0,
						layout:'vbox',
						items: [{
							fieldLabel: 'Template Name',
							name: 'templateName',
							id: 'templateName',
							xtype:'textfield',
							width: 270
						},{
							xtype:'checkbox',
							fieldLabel:'Is public',
							//labelAlign:'right',
							id:'chkIsPublick'
						}]
					});
					templatePnl = Ext.create('Ext.Window', {
						title: 'Save as Template',
						border:0,
						modal:true,
						buttonAlign : "center",
						defaultType: 'textfield',
						width:300,
						height:130,
						defaults: {
							anchor: '100%'
						},
						items: [templateForm],
						buttonAlign:'center',
						buttons: [{
							text: 'Save',
							id:'btnSave',
							handler: function() {
								var isPublic=Ext.getCmp('chkIsPublick').getValue();
								var templateName=Ext.getCmp('templateName').getValue();
								if(templateName==''){
									Ext.MessageBox.alert('Warning', 'Please fill in the template name.');
									return;
								}
								Ext.getBody().mask('processing...');
								Ext.Ajax.request({ 
									url: 'saveOrderTemplate.action',
									method: 'post', 
									params: {
										orderId:<%=order.getOrderId()%>,
										templateName:templateName,
										isPublic:isPublic
									},
									success: function(result, request) { 
										Ext.getBody().unmask();
										var ret = Ext.decode(result.responseText);
										if(ret.state==0){
											templatePnl.hide();
											flashMessage(ret.message,'btnSave',1500);
										}else{
											Ext.MessageBox.alert('Warning', ret.message);
										}
									}, 
									failure: function(result, request) { 
										Ext.getBody().unmask();
										var ret = Ext.decode(result.responseText);
										Ext.MessageBox.alert('Warning', ret.message);
									}
								});
							}
						},
						{
							text: 'Cancel',
							handler: function() {
								templateForm.getForm().reset();
								templatePnl.hide();
							}
						}],
						closeAction: function(){
							templatePnl.hide();
						}
					});
				}
				templatePnl.show();
			}
		}]});
	}
});
</script>

<%@ include file="footer.jsp"%>